package com.birdboot.core;

import com.birdboot.controller.UserController;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.net.URISyntaxException;

/**
 * 该类实际上是SpringMVC框架的一个核心类,用于与服务器(Tomcat)整合,接手处理请求的工作
 */
public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();
    private static File baseDir;//类加载路径
    private static File staticDir;//类加载路径下的static目录
    static {
        try {
            baseDir = new File(
               ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(baseDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private DispatcherServlet(){}

    public static DispatcherServlet getInstance(){
        return instance;
    }

    public void service(HttpServletRequest request, HttpServletResponse response){
        //对于表单上传的抽象路径而言，由于附带参数，因此无法再作为请求判断了
//        String path = request.getUri();
        //requestURI属性在请求对象中就是保存抽象路径的请求路径部分，不含有参数
        String path = request.getRequestURI();
        System.out.println("抽象路径:"+path);

        //首先判断请求路径是否为请求业务
        if("/regUser".equals(path)){
            UserController controller = new UserController();
            controller.reg(request,response);
        }else if("/loginUser".equals(path)){
//            UserController controller = new UserController();
//            controller.login(request,response);
        }else {
            File file = new File(staticDir, path);
            if (file.isFile()) {//file表示的是一个实际存在的文件
                response.setStatusCode(200);
                response.setStatusReason("OK");
                response.addHeader("Server", "BirdServer");
                response.setContentFile(file);
            } else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir, "404.html");
                response.addHeader("Server", "BirdServer");
                response.setContentFile(file);
            }
        }
    }
}
